package com.woniu.permissions.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.client.StaffClient;
import com.woniu.client.model.EmployeeDto;
import com.woniu.exception.RebornException;
import com.woniu.exception.account.AccountException;
import com.woniu.exception.account.AccountExceptionCode;
import com.woniu.model.Result;
import com.woniu.permissions.dto.AccountDto;
import com.woniu.permissions.mapper.AccountRoleMapper;
import com.woniu.permissions.model.Account;
import com.woniu.permissions.mapper.AccountMapper;
import com.woniu.permissions.model.AccountRole;
import com.woniu.permissions.param.AccountLoginParam;
import com.woniu.permissions.param.AddAccountParam;
import com.woniu.permissions.param.AddUserAccountParam;
import com.woniu.permissions.param.UpdateAccountStateParam;
import com.woniu.permissions.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.RedisUtil;
import com.woniu.utils.JwtUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private AccountRoleMapper accountRoleMapper;

    @Resource
    private StaffClient staffClient;
    /**
     * 新增员工账号
     * @param toBean 新增对象
     * @return 返回成功的对象
     */
    @Override
    public Account addAccount(AddAccountParam toBean) {
        Account account = BeanUtil.toBean(toBean,Account.class);
        account.setAccountState(0);
        accountMapper.insert(account);
        return account;
    }
    /**
     * 根据手机账号查询员工账号
     * @param phone 手机号
     * @return 返回账号
     */
    @Override
    public Account selectAccount(String phone) {
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("account_phone", phone).ne("account_state","1");
        Account account = accountMapper.selectOne(wrapper);
        return account;
    }

    /**
     * 测试
     * @return 测试成功
     */
    @Override
    public String gettest() {
        return "测试成功";
    }

    /**
     * 根据账号id查询账号
     * @param accountId 账号id
     * @return 存在返回true 不存在返回false
     */
    @Override
    public Account findAccountByAccountId(String accountId) {
        Account account = accountMapper.selectById(accountId);
        return account;
    }

    /**
     * 根据账号id修改账号状态
     * @param toBean 账号id 状态码
     * @return 返回修改后账号
     */
    @Override
    public Account updateAccountById(UpdateAccountStateParam toBean) {
        Account account = accountMapper.selectById(toBean.getAccountId());
        if (account==null){
            throw new AccountException(AccountExceptionCode.ACCOUNT_NO_ACCOUNT);
        }
        account.setAccountState(toBean.getState());
        accountMapper.updateById(account);
        return account;
    }
    /**
     * 登录
     * @param toBean 登录对象
     * @return
     */
    @Override
    public AccountDto login(AccountLoginParam toBean) {
        QueryWrapper<Account> queryWrapper = new QueryWrapper<Account>();
        queryWrapper.eq("account_phone",toBean.getAccountId());
        queryWrapper.eq("account_state",0);
        Account account = accountMapper.selectOne(queryWrapper);
        System.out.println(account);
        AccountRole role = accountRoleMapper.selectOne(new QueryWrapper<AccountRole>().eq("account_id", account.getAccountId()));

        if (account==null)throw new AccountException(AccountExceptionCode.ACCOUNT_NOT_REGISTER);
        if (!account.getAccountPass().equals(toBean.getPassWord()))throw new AccountException(AccountExceptionCode.ACCOUNT_PASSWORD_ERROR);
//        queryWrapper.eq("account_pass",accountParam.getAccountPass());
//        account = accountMapper.selectOne(queryWrapper);
        //加密判断  state.password_key加盐   用户作为密钥对密码加密得到独特密文
//        String salt=accountParam.getAccountName();
//        int index=0;
//        int count=2;
//        MD5 md5 = new MD5(salt.getBytes(StandardCharsets.UTF_8), index, count);//返回16进制格式
//        if (!md5.digestHex(account.getAccountName()).equals(account.getAccountPass()))throw new AccountException(AccountExceptionCode.ACCOUNT_NOT_DATE);
        AccountDto accountDto = BeanUtil.toBean(account, AccountDto.class);
        accountDto.setRole(Math.toIntExact(role.getRoleId()));
        switch (Math.toIntExact(role.getRoleId())){
            case 2:{
//                System.out.println("9999999!!!");
                employToken(accountDto);
                break;
            }
            case 3:{
//                System.out.println("进来了!!!");
                stationBossToken(accountDto);
                break;
            }
            case 4:{
//                System.out.println("5515151!!!");
                adminToken(accountDto);
                break;
            }
        }
        Result<EmployeeDto> result = staffClient.byAccountId(account.getAccountId());
        if (result.getCode()!=200){
            throw new RebornException(result.getMessage(),result.getCode());
        }
        EmployeeDto data = result.getData();
        if (data!=null){
            accountDto.setStationId(Math.toIntExact(data.getStationId()));
        }
        return accountDto;
    }

    /**
     * 新增用户账号
     * @param param
     * @return
     */
    @Override
    public Account addUserAccount(AddUserAccountParam param) throws Exception {
        Account account = BeanUtil.toBean(param, Account.class);
        account.setAccountState(0);
        save(account);
        return account;
    }


    /**
     * 根据用户名查询 账号对象
     * @param phone
     * @return
     */
    @Override
    public Account byPhone(String phone) {
        return accountMapper.selectOne(new QueryWrapper<Account>().eq("account_phone", phone));
    }

    /**
     * 该方法用于返回一个 员工token
     * @param user 员工dto
     * @return
     */
    private String employToken(AccountDto user){
        HashMap<String, Object> accessBody = new HashMap<>();

        String random = new Snowflake(1, 1).nextIdStr();
        accessBody.put("random",random);
        //生成不重复的随机数 返回给前端 30分钟过期
        String accessToken = JwtUtil.createEmployToken("token", accessBody);

        //已返回给前端的token作为key,存入带敏感数据的token到redis
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String refreshToken = JwtUtil.createToken(map,24*3600,JwtUtil.employSecret);
        redisUtil.set(accessToken,refreshToken,24*3600);//redis的过期时间为1天
        //HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        HttpServletResponse resp = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
        resp.setHeader("token",accessToken);
        resp.setHeader("Access-Control-Expose-Headers","token");
        return accessToken;
    }

    /**
     * 该方法用于返回一个 站长token
     * @param user 员工dto
     * @return
     */
    private String stationBossToken(AccountDto user){
        System.out.println(user);
        HashMap<String, Object> accessBody = new HashMap<>();

        String random = new Snowflake(1, 1).nextIdStr();
        accessBody.put("random",random);
        //生成不重复的随机数 返回给前端 30分钟过期
        String accessToken = JwtUtil.createStationBossToken("token", accessBody);
        System.out.println(accessToken);
        //已返回给前端的token作为key,存入带敏感数据的token到redis
        Map<String, Object> map = BeanUtil.beanToMap(user);
//        map.forEach((k,v)-> System.out.println(map.get(k)));
        String refreshToken = JwtUtil.createToken(map,24*3600,JwtUtil.stationBossSecret);
        System.out.println(refreshToken);
        redisUtil.set(accessToken,refreshToken,24*3600);//redis的过期时间为1天
        //HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        HttpServletResponse resp = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
        resp.setHeader("token",accessToken);
        resp.setHeader("Access-Control-Expose-Headers","token");
        return accessToken;
    }

    /**
     * 该方法用于返回一个 管理员token
     * @param user 管理员dto
     * @return
     */
    private String adminToken(AccountDto user){
        HashMap<String, Object> accessBody = new HashMap<>();

        String random = new Snowflake(1, 1).nextIdStr();
        accessBody.put("random",random);
        //生成不重复的随机数 返回给前端 30分钟过期
        String accessToken = JwtUtil.createAdminToken("token", accessBody);

        //已返回给前端的token作为key,存入带敏感数据的token到redis
        Map<String, Object> map = BeanUtil.beanToMap(user);
        String refreshToken = JwtUtil.createToken(map,24*3600,JwtUtil.adminSecret);
        redisUtil.set(accessToken,refreshToken,24*3600);//redis的过期时间为1天
        //HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        HttpServletResponse resp = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getResponse();
        resp.setHeader("token",accessToken);
        resp.setHeader("Access-Control-Expose-Headers","token");
        return accessToken;
    }
}
